package com.paishen.peiniwan.module.profile;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.util.DateUtil;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.RecyclerAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.Book;
import com.paishen.peiniwan.frame.http.entity.Date;
import com.paishen.peiniwan.frame.http.entity.DateInfo;
import com.paishen.peiniwan.frame.http.entity.User;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.common.widget.MaterialHeader;
import com.paishen.peiniwan.frame.widget.PagerSlidingTabStrip;
import com.paishen.peiniwan.module.date.DateChooseActivity;
import com.paishen.peiniwan.module.date.DateCommentActivity;
import com.paishen.peiniwan.module.date.DateInfoActivity;
import com.squareup.okhttp.Request;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;


public class MainProfileDateLayout extends LinearLayout {
    private PagerSlidingTabStrip pagerStrip;
    private ViewPager viewPager;
    private DatePagerAdapter adapter;

    public MainProfileDateLayout(Context context) {
        this(context, null);
    }

    public MainProfileDateLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // interrupt click event
            }
        });

        LayoutInflater.from(context).inflate(R.layout.layout_main_profile_date, this);
//        ((ViewGroup) getChildAt(0)).getChildAt(0).setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);
        setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);

        pagerStrip = (PagerSlidingTabStrip) findViewById(R.id.pager_strip);
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        viewPager.setAdapter(adapter = new DatePagerAdapter(context, viewPager));

        pagerStrip.setViewPager(viewPager);
        pagerStrip.setBackgroundColor(0xFFF4F5F9);
        // 设置Tab是自动填充满屏幕的
        pagerStrip.setShouldExpand(true);
        // 设置Tab的分割线是透明的
        pagerStrip.setDividerColor(Color.TRANSPARENT);
        // 设置Tab底部线的高度
        pagerStrip.setUnderlineHeight(1);
        // 设置Tab Indicator的高度
        pagerStrip.setIndicatorHeight(BaseUtil.dip2px(1));
        // 设置Tab标题文字的大小
        pagerStrip.setTextSize(BaseUtil.dip2px(15));
        // 设置Tab Indicator的颜色
        pagerStrip.setIndicatorColor(0xFFFC4E52);
        // 设置选中Tab文字的颜色 (这是我自定义的一个方法)
        pagerStrip.setSelectedTextColor(0xFFFC4E52);
        // 取消点击Tab时的背景色
        pagerStrip.setTabBackground(0);
    }

    public void refresh() {
        adapter.getDateLayoutView(0).requestGetOrder();
        adapter.getDateLayoutView(1).requestGetBook();
    }

    private static final class DatePagerAdapter extends PagerAdapter {
        private final List<DateLayout> viewList = new ArrayList<>();

        public DatePagerAdapter(Context context, ViewPager pager) {
            DateLayout order = new DateLayout(context, DateAdapter.TYPE_ORDER);
            order.initPager(pager);
            viewList.add(order);
            DateLayout book = new DateLayout(context, DateAdapter.TYPE_BOOK);
            book.initPager(pager);
            viewList.add(book);
        }

        public DateLayout getDateLayoutView(int position) {
            if (position < viewList.size()) {
                return viewList.get(position);
            }
            return null;
        }

        @Override
        public int getCount() {
            return viewList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return App.i().getString(R.string.date_push);
                case 1:
                    return App.i().getString(R.string.date_pull);
            }
            return null;
        }


        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(viewList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(viewList.get(position));
            return viewList.get(position);
        }
    }

    private static final class DateLayout extends FrameLayout {
        private final DateAdapter adapter;
        private final RecyclerView viewRecycler;
        private final PtrFrameLayout layPtrFrame;
        private final LinearLayoutManager layoutManager;

        private boolean reqLoad;
        private boolean fetchOver = false;
        private long lastid = -1;

        private byte mPagerType;
        private ViewPager mViewPager;

        public DateLayout(Context context, final byte type) {
            super(context);
            mPagerType = type;
            LayoutInflater.from(context).inflate(R.layout.frame_layout_recycler_simple, this);

            layPtrFrame = (PtrFrameLayout) findViewById(R.id.lay_ptr_frame);
            viewRecycler = (RecyclerView) findViewById(R.id.view_recycler);
            viewRecycler.setLayoutManager(layoutManager = new LinearLayoutManager(getContext()));
            viewRecycler.setAdapter(adapter = new DateAdapter(type));
            viewRecycler.setItemAnimator(new DefaultItemAnimator());
            viewRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
                int spacing = BaseUtil.dip2px(10);

                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    outRect.top = spacing;
                }
            });

            viewRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
                private boolean scrollDown = false;

                @Override
                public void onScrolled(RecyclerView viewRecycler, int dx, int dy) {
                    super.onScrolled(viewRecycler, dx, dy);
                    scrollDown = dy > 0;
                }

                @Override
                public void onScrollStateChanged(RecyclerView viewRecycler, int newState) {
                    super.onScrollStateChanged(viewRecycler, newState);
                    switch (newState) {
                        case RecyclerView.SCROLL_STATE_IDLE:
                            int lastVisibleItem = layoutManager.findLastCompletelyVisibleItemPosition();
                            int totalItemCount = layoutManager.getItemCount();
                            if (lastVisibleItem >= (totalItemCount - 1) && scrollDown) {
                                if (!fetchOver) {
                                    switch (type) {
                                        case DateAdapter.TYPE_BOOK:
                                            requestGetBook(lastid);
                                            break;
                                        case DateAdapter.TYPE_ORDER:
                                            requestGetOrder(lastid);
                                            break;
                                    }
                                }
                            }

                            break;
                        case RecyclerView.SCROLL_STATE_DRAGGING:
                            break;
                    }
                }
            });


            MaterialHeader header = new MaterialHeader(getContext());
            int[] colors = new int[]{0xFF05131A};
            header.setColorSchemeColors(colors);
            header.setLayoutParams(new FrameLayout.LayoutParams(-1, -2));
            header.setPadding(0, BaseUtil.dip2px(15), 0, BaseUtil.dip2px(10));
            header.setPtrFrameLayout(layPtrFrame);
            layPtrFrame.setDurationToCloseHeader(1500);
            layPtrFrame.setHeaderView(header);
            layPtrFrame.addPtrUIHandler(header);
            layPtrFrame.setPtrHandler(new PtrHandler() {
                @Override
                public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                    return PtrDefaultHandler.checkContentCanBePulledDown(frame, viewRecycler, header);
                }

                @Override
                public void onRefreshBegin(final PtrFrameLayout frame) {
                    switch (type) {
                        case DateAdapter.TYPE_BOOK:
                            lastid = -1;
                            requestGetBook(lastid);
                            break;
                        case DateAdapter.TYPE_ORDER:
                            lastid = -1;
                            requestGetOrder(lastid);
                            break;
                    }
                }
            });

            layPtrFrame.postDelayed(runRequest, 500);
        }

        private Runnable runRequest = new Runnable() {
            @Override
            public void run() {
                layPtrFrame.autoRefresh();
            }
        };

        @Override
        protected void onDetachedFromWindow() {
            super.onDetachedFromWindow();
            layPtrFrame.removeCallbacks(runRequest);
        }

        public void initPager(ViewPager viewPager) {
            mViewPager = viewPager;
        }

        public void requestGetBook() {
            lastid = -1;
            requestGetBook(lastid);
        }

        public void requestGetBook(final long lid) {
            if (reqLoad) return;
            reqLoad = true;

            adapter.refreshLoadState(true);
            PnwHttpManager.Order.getBook(((BaseActivity) getContext()).TAG, lid, new PnwOkCallbackAdapter<HttpRespData<List<Date>>>() {
                @Override
                public void onResponse(HttpRespData<List<Date>> response, boolean fresh) {
                    super.onResponse(response, fresh);
                    layPtrFrame.refreshComplete();
                    reqLoad = false;
                    fetchOver = false;
                    lastid = -1;


                    if (response.errcode == C.http.RESULT_SUCCESS) {

                        if (response.data != null && response.data.size() > 0) {
                            fetchOver = response.data.size() < DateAdapter.FETCH_COUNT;

                            lastid = response.data.get(response.data.size() - 1).id;

                            boolean b = lid < 0 ? adapter.set(response.data, fetchOver) : adapter.append(response.data, fetchOver);
                        } else {
                            if (mViewPager.getCurrentItem() == mPagerType) {
                                BaseUtil.showToast(response.errmsg);
                            }

                            fetchOver = true;
                            boolean b = lid > 0 ? adapter.refreshLoadState(false) : adapter.set(new ArrayList<Date>(), true);
                        }

                    } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                            response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                        BaseUtil.showToast(response.errmsg);
                        adapter.refreshLoadState(false);
                    }
                }

                @Override
                public void onFailure(Request request, Exception e) {
                    super.onFailure(request, e);
                    layPtrFrame.refreshComplete();
                }
            });
        }

        public void requestGetOrder() {
            lastid = -1;
            requestGetOrder(lastid);
        }

        public void requestGetOrder(final long lid) {
            if (reqLoad) return;
            reqLoad = true;

            adapter.refreshLoadState(true);
            PnwHttpManager.Order.getOrder(((BaseActivity) getContext()).TAG, lid, new PnwOkCallbackAdapter<HttpRespData<List<Date>>>() {
                @Override
                public void onResponse(HttpRespData<List<Date>> response, boolean fresh) {
                    super.onResponse(response, fresh);
                    layPtrFrame.refreshComplete();
                    reqLoad = false;
                    fetchOver = false;
                    lastid = -1;

                    if (response.errcode == C.http.RESULT_SUCCESS) {

                        if (response.data != null && response.data.size() > 0) {
                            fetchOver = response.data.size() < DateAdapter.FETCH_COUNT;

                            lastid = response.data.get(response.data.size() - 1).id;

                            boolean b = lid < 0 ? adapter.set(response.data, fetchOver) : adapter.append(response.data, fetchOver);
                        } else {
                            if (mViewPager.getCurrentItem() == mPagerType) {
                                BaseUtil.showToast(response.errmsg);
                            }

                            fetchOver = true;
                            boolean b = lid > 0 ? adapter.refreshLoadState(false) : adapter.set(new ArrayList<Date>(), true);
                        }

                    } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                            response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                        BaseUtil.showToast(response.errmsg);
                        adapter.refreshLoadState(false);
                    }
                }

                @Override
                public void onFailure(Request request, Exception e) {
                    super.onFailure(request, e);
                    layPtrFrame.refreshComplete();
                }
            });
        }
    }

    private static final class DateAdapter extends RecyclerAdapter {

        private static final byte TYPE_ORDER = 0;
        private static final byte TYPE_BOOK = 1;

        private final String[] date_status;

        private final byte type;
        private final ViewGroup.MarginLayoutParams lpSubject;
        private final int d5;

        public DateAdapter(byte type) {
            this.type = type;
            d5 = BaseUtil.dip2px(5);
            lpSubject = new ViewGroup.MarginLayoutParams(BaseUtil.dip2px(65), BaseUtil.dip2px(25));
            lpSubject.setMargins(0, 0, d5, d5);

            date_status = App.i().getResources().getStringArray(R.array.date_status);
        }

        public class ViewHolderItem extends RecyclerView.ViewHolder implements OnClickListener {
            public ViewHolderItem(View view) {
                super(view);
                view.setOnClickListener(this);
            }

            private Date itemData;
            private ViewGroup laySubject;
            private TextView txNickname, txTime, txStatus;
            private ImageView imgAvatar;

            @Override
            public void onClick(View v) {
                switch (type) {
                    case TYPE_BOOK: // 我的应约
                        if (itemData.status == C.date.WAIT_RESPONSE_1
                                || itemData.status == C.date.WAIT_PAY_2
                                || itemData.status == C.date.RUNNING_3
                                || itemData.status == C.date.WAIT_COMMENT_4
                                || itemData.status == C.date.COMPLETED_5
                                || itemData.status == C.date.FAILURE_7
                                || itemData.status == C.date.CANCELLED_9
                                || itemData.status == C.date.WAIT_RUN_10) {
                            Intent intent = new Intent(v.getContext(),
                                    itemData.status == C.date.WAIT_COMMENT_4 ? DateCommentActivity.class : DateInfoActivity.class);

                            Book eb = new Book();
                            eb.id = itemData.bid;
                            User u = new User();
                            u.id = App.i().getUser().getId();
                            eb.user = u; // 我的应约，responder 是我 放在book 里面
                            eb.unit_price = itemData.price;
                            DateInfo e = new DateInfo();
                            e.id = itemData.id;
                            e.user = itemData.OrderUser;// 下单人是对方的信息
                            e.book = new ArrayList<>();
                            e.book.add(eb);
                            e.subject_type = itemData.subject_type;
                            e.date_from = itemData.date_from;
                            e.address = itemData.address;
                            // 注 这里要反过来 isSelfpay 表示订单创建者是否给了礼物 ?? 服务器处理过了？
                            e.isself_pay = itemData.isself_pay;
                            e.sex = itemData.sex;
                            e.status = itemData.status;
                            intent.putExtra(DateInfoActivity.EXTRA_DATE_INFO, e);
                            v.getContext().startActivity(intent);
                        }
                        break;
                    case TYPE_ORDER: // 我的邀约
                        if (itemData.status == C.date.WAIT_RESPONSE_1
                                || itemData.status == C.date.FAILURE_7) {
                            Intent intent = new Intent(v.getContext(), DateChooseActivity.class);
                            intent.putExtra(DateChooseActivity.EXTRA_ORDER_ID, itemData.id);
                            v.getContext().startActivity(intent);
                        } else if (itemData.status == C.date.WAIT_PAY_2
                                || itemData.status == C.date.RUNNING_3
                                || itemData.status == C.date.WAIT_COMMENT_4
                                || itemData.status == C.date.COMPLETED_5
                                || itemData.status == C.date.CANCELLED_9
                                || itemData.status == C.date.WAIT_RUN_10) {
                            Intent intent = new Intent(v.getContext(),
                                    itemData.status == C.date.WAIT_COMMENT_4 ? DateCommentActivity.class : DateInfoActivity.class);

                            Book eb = new Book();
                            eb.id = itemData.bid;
                            eb.user = itemData.TargetUser; // responder是放在book里面 [我的邀约]
                            eb.unit_price = itemData.price;
                            DateInfo e = new DateInfo();
                            e.id = itemData.id;
                            User u = new User();
                            u.id = App.i().getUser().getId();
                            e.user = u; // 我的邀约，发单人我是
                            e.book = new ArrayList<>();
                            e.book.add(eb);
                            e.subject_type = itemData.subject_type;
                            e.date_from = itemData.date_from;
                            e.address = itemData.address;
                            e.isself_pay = itemData.isself_pay;
                            e.sex = itemData.sex;
                            e.status = itemData.status;
                            intent.putExtra(DateInfoActivity.EXTRA_DATE_INFO, e);
                            v.getContext().startActivity(intent);
                        }
                        break;
                }
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
            switch (type) {
                case Element.TYPE_ITEM:
                    View viewItem = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_main_profile_date, viewGroup, false);
                    ViewHolderItem vhItem = new ViewHolderItem(viewItem);
                    vhItem.laySubject = (ViewGroup) viewItem.findViewById(R.id.lay_subject);
                    vhItem.txNickname = (TextView) viewItem.findViewById(R.id.tx_nickname);
                    vhItem.txTime = (TextView) viewItem.findViewById(R.id.tx_time);
                    vhItem.txStatus = (TextView) viewItem.findViewById(R.id.tx_status);
                    vhItem.imgAvatar = (ImageView) viewItem.findViewById(R.id.img_avatar);
                    // vhItem.imgAvatar.setOnClickListener(onHeadClickListener);
                    return vhItem;
            }
            return super.onCreateViewHolder(viewGroup, type);
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
            super.onBindViewHolder(viewHolder, position);
            Element e = elements.get(position);
            switch (e.type) {
                case Element.TYPE_ITEM:
                    final Date date = (Date) e.element;
                    User user = null;
                    switch (type) {
                        case TYPE_BOOK:
                            user = date.OrderUser;
                            break;
                        case TYPE_ORDER:
                            user = date.TargetUser;
                            break;
                    }

                    ViewHolderItem vhItem = (ViewHolderItem) viewHolder;

                    if (user != null && !TextUtils.isEmpty(user.head_img_url)) {
                        Glide.with(viewHolder.itemView.getContext()).load(user.head_img_url).bitmapTransform(App.i().getCropCircleTransformation())
                                .into(vhItem.imgAvatar);
                    }

                    vhItem.txNickname.setText(user != null ? user.nickname : "");
                    vhItem.txTime.setText(DateUtil.convert(date.date_from, DateUtil.yyyy_MM_dd_HH_mm_ss, DateUtil.MM_dd_HH_mm));

                    vhItem.laySubject.removeAllViewsInLayout();
                    for (String subject : date.subject_type) {
                        vhItem.laySubject.addView(makeTagView(viewHolder.itemView.getContext(), subject));
                    }

                    vhItem.txStatus.setText(date_status[date.status]);
                    if (date.status == C.date.WAIT_RESPONSE_1) {
                        switch (type) {
                            case TYPE_BOOK:
                                vhItem.txStatus.setText(date_status[C.date.RESPONSED_6]);
                                break;
                            case TYPE_ORDER:
                                if (date.book_count != 0) {
                                    vhItem.txStatus.setText(App.i().getString(R.string.date_responder_count_3, String.valueOf(date.book_count)));
                                }
                                break;
                        }
                    }

                    vhItem.itemData = date;
                    break;
            }
        }

        private TextView makeTagView(Context context, String text) {
            TextView txSubject = new TextView(context);
            txSubject.setLayoutParams(lpSubject);
            txSubject.setTextColor(0xFFFFFFFF);
            txSubject.setTextSize(13);
            txSubject.setGravity(Gravity.CENTER);
            txSubject.setText(text);
            txSubject.setBackgroundResource(R.drawable.date_shape_subject);
            return txSubject;
        }
    }


}
